----------------------------------------
-- 陀螺仪功能
----------------------------------------
local M = {}

local pi = math.pi

function M.isEnable()
	return system.hasEventSource("gyroscope")
end

function M.event(params)
	local onEvent = params.onEvent or function() end

	local count = 0
	local ranTodeg = 180/pi

	local totalX, totalY, totalZ = 0, 0, 0
	local function onGyroscopeDataReceived( event )
		count = count + 1
		if count % 1 == 0 then
			totalX = (event.xRotation*event.deltaTime*ranTodeg+ totalX)%360
			totalY = (event.yRotation*event.deltaTime*ranTodeg+ totalY)%360
			totalZ = (event.zRotation*event.deltaTime*ranTodeg+ totalZ)%360
			onEvent(totalX, totalY, totalZ)
			
			count = 0
		end 
	end
	  
	if M.isEnable() then
	    Runtime:addEventListener( "gyroscope", onGyroscopeDataReceived )
	end
end

function M.test()
	local function createText()
		local gText = display.newGroup()

		local txtX = display.newText({
			text = "",
			fontSize = 25,
			-- align = "left",
			parent = gText
		})
		txtX.anchorX = 0

		local txtY = display.newText({
			text = "",
			fontSize = 25,
			align = "left",
			parent = gText,
			y = txtX.y + txtX.height + 10,
		})
		txtY.anchorX = 0

		local txtZ = display.newText({
			text = "",
			fontSize = 25,
			align = "left",
			parent = gText,
			y = txtY.y + txtY.height + 10,
		})
		txtZ.anchorX = 0

		function gText:update(x, y, z)
			txtX.text = "X : " .. x
			txtY.text = "Y : " .. y
			txtZ.text = "Z : " .. z
		end

		return gText
	end

	local gText = createText()
	gText.x = SCREEN_CX - 60
	gText.y = SCREEN_CY

	local function onEvent(totalX, totalY, totalZ)
		gText:update(totalX, totalY, totalZ)
	end
	M.event({onEvent = onEvent})
end

function M.init()
	-- M.test()
end

return M